package com.coocaa.x.framework.utils;

import android.content.res.AssetManager;
import android.util.Xml;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.data.InstallBackData;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.tianci.media.api.Log;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by admin on 2015/11/18.
 */
public class PresetUtil {

    public static void PresetApp() {
        InstallBackData data = new InstallBackData();
        try {
            String[] fArry = CoocaaApplication.getContext().getAssets().list("preset/apk");
            if (fArry != null && fArry.length > 0) {
                Map<String, String> cmdMap = null;
                for (int i = 0; i < fArry.length; i++) {
                    LogUtils.d("preset", "path:" + fArry[i]);
                    if (fArry[i].endsWith(".mp3")) {
                        data = silentInstallApp(fArry[i]);
                        submitPreInstallLog(data);
                    }
                    else if (fArry[i].endsWith(".xml"))
                        cmdMap = getPresetConfig(fArry[i]);
                }
                if(cmdMap != null && cmdMap.size() > 0)
                {
                    for(String key:cmdMap.keySet()){
                        execCommand(cmdMap.get(key));
                    }
                }
            }
            else{
                data.setData(-1,null,"");
                submitPreInstallLog(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            data.setData(-1, null, "");
            submitPreInstallLog(data);
        }
    }

    private static InstallBackData silentInstallApp(String file) {
        InstallBackData data = new InstallBackData();
        String path = CoocaaApplication.getContext().getCacheDir().getAbsolutePath()
                + "/" + file.substring(0,file.lastIndexOf("."))+".apk";
        try {
            InputStream is = CoocaaApplication.getContext().getResources().getAssets().open("preset/apk/"+file);
            FileOutputStream fs = new FileOutputStream(path);
            byte[] buffer = new byte[4096];
            int byteread;
            while ((byteread = is.read(buffer)) != -1)
                fs.write(buffer, 0, byteread);
            is.close();
            fs.close();

            Runtime.getRuntime().exec("chmod 777 " + path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        AppInfo info = PMUtils.getAPKInfo(path);
        LogUtils.d("preset", "silentInstallApp  path:" + path + " info != null :" + (info != null));
        if (info != null && info.pkgName != null) {
            boolean isInstalled = PMUtils.isAppInstalled(info.pkgName);
            LogUtils.d("preset", "silentInstallApp  isInstalled:" + isInstalled + "  pkg:" + info.pkgName);
            if (!isInstalled)
                data = PMUtils.installAPP(path, true, false);
            else{
                data.setData(-1,info,"app is installed ");
            }
        }
        else{
            data.setData(1,null,"path is error,has no appInfo");
        }
        LogUtils.d("preset", "silentInstallApp  installSuccess:" + data.installStatus);
        File f = new File(path);
        if (f.exists())
            f.delete();
        return data;
    }

    private static void execCommand(String cmd){
        LogUtils.d("preset", "execCommand cmd: "+cmd);
        ShellUtils.CommandResult commandResult = ShellUtils.execCommand(cmd, true, true);
        LogUtils.d("preset", "execCommand   commandResult: "+commandResult.successMsg);
        if (commandResult.successMsg != null
                && (commandResult.successMsg.contains("Starting") || commandResult.successMsg
                .contains("Starting"))) {
            LogUtils.d("preset", "execCommand success  !! ");
        } else {// fail
            LogUtils.d("preset", "execCommand failed !!   ");
        }
    }

    private static Map<String, String> getPresetConfig(String path) {
        Map<String, String> presetConfig = new HashMap<String, String>();
        try {
            AssetManager am = CoocaaApplication.getContext().getAssets();
            InputStream is = am.open("preset/apk/" + path);
            XmlPullParser xmlParser = Xml.newPullParser();
            try {
                xmlParser.setInput(is, "utf-8");
                int event = xmlParser.getEventType();
                while (event != XmlPullParser.END_DOCUMENT) {
                    switch (event) {
                        case XmlPullParser.START_DOCUMENT:
                            break;
                        case XmlPullParser.START_TAG:
                            if ("app".equals(xmlParser.getName())) {
                                String pkg = xmlParser.getAttributeValue(null, "package");
                                String value = xmlParser.getAttributeValue(null, "value");
                                LogUtils.d("preset", "getPresetConfig  pkg value:" + pkg + " " + value);
                                presetConfig.put(pkg, value);
                            }
                            break;
                        case XmlPullParser.END_TAG:
                            break;
                    }
                    event = xmlParser.next();
                }
                is.close();
            } catch (XmlPullParserException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return presetConfig;
    }

    private static void submitPreInstallLog(InstallBackData data) {
        LogUtils.d("preset","submitPreInstallLog   res:"+data.installStatus+" extra:"+data.extra);
        LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "preinstall_app");
        switch (data.installStatus) {
            case -1:
                log.addParam("status", "不用预置安装");
                break;
            case 0:
                log.addParam("status", "安装成功");
                break;
            case 1:
                log.addParam("status", "安装失败");
                log.addParam("error", data.extra);
                break;
        }
//        if (data.installSuccess)
//            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "preinstall_app_onsuccess");
//        else {
//            log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE, "preinstall_app_onfailed");
//            log.addParam("error",data.extra);
//        }
        if (data.info != null)
            log.addParam("app", data.info.pkgName + "@" + data.info.versionCode);
        LogUtils.submit(log);
    }

}
